package com.ruoyi.base.filter;

import com.dyun.tool.jwt.utils.JWTUtil;
import com.dyun.tool.mybatis.util.MPContextHolder;
import com.dyun.tool.ssecurity.utils.YunSecurityUtils;
import com.ruoyi.project.setting.security.LoginUser;
import com.ruoyi.project.setting.security.utils.UserUtils;
import com.ruoyi.project.system.entity.SysUser;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author dyun
 */
@Slf4j
public class TenantReqFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        try {
            Map<String, Object> user = JWTUtil.getUser((HttpServletRequest) request);
            if (user != null) {
                LoginUser loginUser = UserUtils.currentLoginUser();
                // 已登陆用户
                SysUser sysUser = loginUser.getSysUser();
                if (YunSecurityUtils.isAdmin(sysUser.getId())) {
                    MPContextHolder.setAdmin();
                }
                MPContextHolder.setTenantId(String.valueOf(sysUser.getTenantId()));
            }
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            log.info(e.getMessage());
        } finally {
            MPContextHolder.clear();
        }
    }

    @Override
    public void destroy() {

    }
}
